package Project;

import UI.ChatMainFrame;

import java.awt.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class CilentReaderThread extends Thread
{
    private Socket socket;
    private DataInputStream dis;
    private ChatMainFrame chatMainFrame;
    public CilentReaderThread(Socket socket, ChatMainFrame chatMainFrame)
         {
         this.socket=socket;
         this.chatMainFrame=chatMainFrame;
         }
    @Override
    public void run()
    {
        try {
           dis =  new DataInputStream(socket.getInputStream());

            while(true)
            {
                int type=dis.readInt();
                switch(type)
                {
                      case 1://更新人数列表
                          UpdateClientOnlineUserList();
                     break;
                     case 2://更新聊天界面
                         UpdateClientChatRoom();
                       break;
                      case 3:break;
                     default:break;
                }
            }



        } catch (Exception e) {
           e.printStackTrace();
        }

    }

    private void UpdateClientChatRoom() throws Exception
    {
       String content=dis.readUTF();
        //更新聊天记录在聊天界面
        chatMainFrame.UpdateChatRoom(content);
    }

    private void UpdateClientOnlineUserList() throws IOException
    {
        //读取用户列表有几个人
        int size=dis.readInt();
        //读入这几个人的数据
        List<String> OnlineNames = new ArrayList<>();
        for(int i=0;i<size;i++)
        {
            String nickname=dis.readUTF();//接一下，第一不接要丢，第二你要展示昵称
            //把昵称添加到集合中
            OnlineNames.add(nickname);
        }
        //更新到聊天窗口界面展示出来
         this.chatMainFrame.updateOnlineUserList(OnlineNames);
    }
}
